package com.itheima.app.manager;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.FocusUser;
import com.itheima.domain.db.Video;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.FocusUserService;
import com.itheima.service.mongo.VideoService;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.PageBeanVo;
import com.itheima.vo.VideoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zsk
 * @create 2022-03-23-16:03
 */
@Component
public class VideoManager {

    @DubboReference
    private VideoService videoService;

    @DubboReference
    private UserInfoService userInfoService;

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;

    @DubboReference
    private FocusUserService focusUserService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //分页查询小视频列表
    public ResponseEntity findVideoByPage(Integer pageNum, Integer pageSize) {

        //获取线程内userId
        Long userId = UserHolder.get().getId();

        //调用rpc查询视频详情
        PageBeanVo pageBeanVo = videoService.findVideoByPage(userId, pageNum, pageSize);

        //封装VideoVo集合对象
        List<VideoVo> voList = new ArrayList<>();

        //显示分页结果
        List<Video> videoList = (List<Video>) pageBeanVo.getItems();
        if (CollectionUtil.isNotEmpty(videoList)) {
            for (Video video : videoList) {
                VideoVo vo = new VideoVo();
                vo.setUserInfo(userInfoService.findById(video.getUserId()));
                vo.setVideo(video);

                //判断我是否关注了视频作者(从Redis中取出标记)
                if (stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.FOCUS_USER, userId, video.getUserId()))) {
                    vo.setHasFocus(1);//已关注
                }
                //添加到voList集合
                voList.add(vo);
            }
        }
        //添加到分页对象中
        pageBeanVo.setItems(voList);

        //返回结果
        return ResponseEntity.ok(pageBeanVo);

    }

    //发布视频
    public void saveVideo(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {

        //获取线程内userId
        Long userId = UserHolder.get().getId();

        // 2 .上传封面
        StorePath storePath1 = client.uploadFile(videoThumbnail.getInputStream() // 文件io流
                , videoThumbnail.getSize() // 文件大小
                , FileUtil.extName(videoThumbnail.getOriginalFilename()) // 文件扩展名
                , null);//  文件元属性
        String picUrl = webServer.getWebServerUrl() + storePath1.getFullPath();
        // 3.上传视频
        StorePath storePath2 = client.uploadFile(videoFile.getInputStream()
                , videoFile.getSize()
                , FileUtil.extName(videoFile.getOriginalFilename())
                , null);
        String videoUrl = webServer.getWebServerUrl() + storePath2.getFullPath();

        //封装video对象
        Video video = new Video();
        video.setId(ObjectId.get());// 视频主键
        video.setCreated(System.currentTimeMillis());//发布时间
        video.setUserId(userId);// 视频发布人
        video.setText("脸红babby");//描述文字
        video.setPicUrl(picUrl);//封面
        video.setVideoUrl(videoUrl);//视频内容

        //调用rpc保存
        videoService.saveVideo(video);
    }

    //关注用户
    public void saveFocus(Long focusUserId) {
        //获取线程内userId
        Long userId = UserHolder.get().getId();
        //封装FocusUser对象
        FocusUser focusUser = new FocusUser();
        focusUser.setCreated(System.currentTimeMillis());//关注时间
        focusUser.setUserId(userId);
        focusUser.setFocusUserId(focusUserId);

        //调用rpc保存
        focusUserService.saveFocusUser(focusUser);

        //像Redis中存储关注标记
        stringRedisTemplate.opsForValue().set(StrUtil.format(ConstantUtil.FOCUS_USER, userId, focusUserId), "1");

    }

    //取消关注
    public void userUnFocus(Long focusUserId) {
        //获取线程内userId
        Long userId = UserHolder.get().getId();

        //调用rpc删除
        focusUserService.removeFocusUser(userId, focusUserId);

        //从Redis中删除标记
        stringRedisTemplate.delete(StrUtil.format(ConstantUtil.FOCUS_USER, userId, focusUserId));


    }
}
